package org.strongme.modules.project.web;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.strongme.common.mapper.JsonMapper;
import org.strongme.common.persistence.Page;
import org.strongme.common.util.excel.ExportExcel;
import org.strongme.common.web.BaseController;
import org.strongme.modules.project.entity.OpGuide;
import org.strongme.modules.project.entity.Project;
import org.strongme.modules.project.entity.SubProject;
import org.strongme.modules.project.entity.Tz;
import org.strongme.modules.project.entity.TzTj;
import org.strongme.modules.project.service.OpGuideService;
import org.strongme.modules.project.service.ProjectService;
import org.strongme.modules.project.service.TzService;
import org.strongme.util.DateUtils;
import org.strongme.util.StringUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Controller
@RequestMapping("project/tz")
public class TzController extends BaseController {

	@Autowired
	private TzService tzService;
	@Autowired
	private OpGuideService opGuideService;
	@Autowired
	private ProjectService projectService;
	@ModelAttribute("tz")
	public Tz get(@RequestParam(required = false) String id, @RequestParam(required = false) String projectId,
			@RequestParam(required = false) String subProjectId, @RequestParam(required = false) String suoxiePro,
			@RequestParam(required = false) String suoxieSub) {
		Tz tz = null;
		if (StringUtils.isNotBlank(id)) {
			tz = tzService.get(new Tz(id));
			if (projectId != null && !"".equals(projectId) && tz != null && tz.getSubProject() != null) {
				tz.getSubProject().setProject(new Project(projectId));
			}
		} else if (StringUtils.isNoneBlank(subProjectId)) {
			tz = new Tz();
			Project p = new Project(projectId);
			p.setSuoxie(suoxiePro);
			SubProject sp = new SubProject(subProjectId);
			sp.setSuoxie(suoxieSub);
			sp.setProject(p);
			tz.setSubProject(sp);
		} else if (StringUtils.isNoneBlank(projectId)) {
			tz = new Tz();
			SubProject sp = new SubProject();
			sp.setProject(new Project(projectId));
			tz.setSubProject(sp);
		} else {
			tz = new Tz();
		}
		return tz;
	}

	@RequestMapping(value = { "index", "" })
	public String Index() {
		return "modules/project/tz/tzIndex.jsp";
	}

	@RequestMapping(value = { "list" })
	public String list(Tz tz, HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam(required = false) String suoxiePro, @RequestParam(required = false) String suoxieSub) {
		Page<Tz> page = tzService.findPage(new Page<Tz>(request, response), tz);
		model.addAttribute("page", page);
		model.addAttribute("suoxiePro", suoxiePro);
		model.addAttribute("suoxieSub", suoxieSub);
		model.addAttribute("page", page);
		model.addAttribute("tz", tz);
		return "modules/project/tz/tzList.jsp";
	}

	@RequestMapping(value = "form")
	public String form(Tz tz, Model model) {
		if (tz.getNotnew() != null && "yes".equals(tz.getNotnew())) {
			tz.setId(null);
			tz.setHkbh(null);
		}
		if (tz.getId() == null || "".equals(tz.getId())) {
			if (tz.getSubProject() != null && tz.getSubProject().getSuoxie() != null
					&& !"".equals(tz.getSubProject().getSuoxie()) && tz.getSubProject().getProject() != null
					&& !"".equals(tz.getSubProject().getProject().getSuoxie())) {
				tz.setXh(tz.getSubProject().getProject().getSuoxie() + "-" + tz.getSubProject().getSuoxie()
						+ "-RTJL-");
			}
		}

		OpGuide og = new OpGuide();
		og.setProject(tz.getSubProject().getProject());
		model.addAttribute("GGList", opGuideService.getGGListByProject(og));

		List<String> czList = opGuideService.loadCzByProjectId(og);
		model.addAttribute("czList", czList);
		model.addAttribute("tz", tz);
		return "modules/project/tz/tzForm.jsp";
	}

	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(Tz tz, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, tz)) {
			return form(tz, model);
		}
		//检测是否存在此焊口编号
		if(tzService.existHkInThisGx(tz)==0||StringUtils.isNotBlank(tz.getId())) {
			tzService.save(tz);
			addMessage(redirectAttributes, "保存台账:'" + tz.getJjmc() + " - " + tz.getGxh() + "'成功");
		}else {
			addMessage(redirectAttributes, "保存台账:'" + tz.getJjmc() + " - " + tz.getGxh() + "'失败,已经存在此台账");
		}
		return "redirect:/project/tz/list?projectId=" + tz.getSubProject().getProject().getId() + "&subProjectId="
				+ tz.getSubProject().getId();
	}

	@RequestMapping(value = "delete")
	public String delete(Tz tz, RedirectAttributes redirectAttributes) {
		tzService.delete(tz);
		addMessage(redirectAttributes, "删除管线检测记录成功");
		return "redirect:/project/tz/list?tz.subProject.id=" + tz.getSubProject().getId();
	}

	@RequestMapping(value = "listGXHBySub", method = RequestMethod.POST)
	@ResponseBody
	public List<Tz> getGxhBySub(@RequestParam String subProjectId) {
		
		List<Tz> result = tzService.getDistinctGXBHListBySubProId(subProjectId);
		if (result == null)
			result = Lists.newArrayList();
		return result;
	}

	@RequestMapping(value = "listGGBySub", method = RequestMethod.POST)
	@ResponseBody
	public List<Tz> getGGBySub(@RequestParam String subProjectId,@RequestParam String gxh) {
		Map<String, Object> param = Maps.newHashMap();
		param.put("subProjectId", subProjectId);
		param.put("gxh", gxh);
		List<Tz> result = tzService.getDistinctGGListBySubProId(param);
		if (result == null)
			result = Lists.newArrayList();
		return result;
	}
	
	@RequestMapping("tj")
	public String tongJiTz(Tz tz, Model model) {
		model.addAttribute("projectList", projectService.findList(new Project()));
		List<Tz> allTz = tzService.findList(tz);
		Map<String, List<Tz>> tzMap = renderTzMap(allTz);
		List<TzTj> result = Lists.newArrayList();
		for(String key : tzMap.keySet()) {
			List<Tz> tl = tzMap.get(key);
			if(tl!=null) {
				result.add(tj(tl, tz.getSxy(), null));
			}
		}
		model.addAttribute("data", result);
		model.addAttribute("tz", tz);
		return "modules/project/tz/tzTj.jsp";
	}
	
	@ResponseBody
	@RequestMapping(value = "checkExist")
	public String checkExistHkbh(Tz tz) {
		String result = "true";
		if(tz==null||StringUtils.isBlank(tz.getGxh())||StringUtils.isBlank(tz.getHkbh())) {
			return "true";
		}
		if(tz.getHkbh().equals(tz.getOldHkbh())) {
			return "true";
		}
		Integer count = tzService.existHkInThisGx(tz);
		if(count>0) {
			result = "false";
		}
		return result;
	}
	
	@RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Tz tz, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String title = "无损检测统计报表";
			if(tz!=null&&tz.getSubProject()!=null&&tz.getSubProject().getProject()!=null&&tz.getSubProject().getProject().getId()!=null &&!"".equals(tz.getSubProject().getProject().getId())) {
				Project p = projectService.get(new Project(tz.getSubProject().getProject().getId()));
				if(p!=null) {
					title = p.getName()+" "+title;
				}
			}
			List<Tz> allTz = tzService.findList(tz);
			Map<String, List<Tz>> tzMap = renderTzMap(allTz);
			List<TzTj> result = Lists.newArrayList();
			for(String key : tzMap.keySet()) {
				List<Tz> tl = tzMap.get(key);
				if(tl!=null) {
					result.add(tj(tl, tz.getSxy(), tz.getGxh()));
				}
			}
			List<String> subTitles = Lists.newArrayList();
			List<TzTj> newResult = Lists.newArrayList();
            if(result.size()>0) {
            	
            	for(int i=0;i<result.size();i++) {
            		TzTj tttmp = result.get(i);
            		tttmp.setXh(String.valueOf(i+1));
            		newResult.add(tttmp);
            	}
             }
        	String sub = "";
        	if(result.size()>0) {
        		TzTj tt = result.get(0);
        		sub += "工程名称："+tt.getGcmc()+"\u0020\u0020\u0020\u0020\u0020\u0020单位工程："+tt.getDwgc();
        	}
        	String wtks  = tz.getWtStartDate()==null?"":tz.getWtStartDate();
        	String wtjs  = tz.getWtEndDate()==null?"":tz.getWtEndDate();
        	String jcks = tz.getJcStartDate()==null?"":tz.getJcStartDate();
        	String jcjs = tz.getJcEndDate()==null?"":tz.getJcEndDate();
        	String gxh = tz.getGxh()==null?"":tz.getGxh();
        	sub+="\u0020\u0020\u0020\u0020\u0020\u0020委托日期："+wtks+"\u0020到\u0020"+wtjs;
        	sub+="\u0020\u0020\u0020\u0020\u0020\u0020检测日期："+jcks+"\u0020到\u0020"+jcjs;
        	sub+="\u0020\u0020\u0020\u0020\u0020\u0020管线（设备）编号："+gxh;
        	subTitles.add(sub);
        	
            String fileName = new String(("无损检测统计报表").getBytes("gbk"),"iso8859-1")+DateUtils.getDate()+".xlsx";
    		new ExportExcel(title,subTitles, TzTj.class).setDataList(newResult).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出无损检测统计报表失败！失败信息："+e.getMessage());
		}
		return "redirect:/project/tz/tj";
    }
	
	/**
	 * 统计不合格焊口数
	 * @param tzList
	 * @return
	 */
	private TzTj tj(List<Tz> tzList, String sxy, String gxh) {
		if(tzList==null||tzList.size()==0) {
			return null;
		}
		Tz now = tzList.get(0);
		//焊口数量: 台账总数
		Integer hks = tzList.size();
		//不合格焊口数
		Integer bhghks = 0;
		//一次焊口合格率
		Integer ychkhgl = 0;
		Integer ychkhglNot = 0;
		//一次拍片数量
		Integer ycppsl = 0;
		//不合格片数量
		Integer bhgpsl = 0;
		//扩探口数量
		Integer ktksl = 0;
		//扩探合格数量
		Integer kthgsl = 0;
		//一次不合格片数量
		Integer ycbhgpsl = 0;

		for(Tz tz: tzList) {
			//统计一次不合格片数量
			if(tz!=null && tz.getFxps()!=null && !"".equals(tz.getFxps())) {
				ycbhgpsl += Integer.valueOf(tz.getFxps());
			}
			//统计一次焊口合格率
			if(tz!=null && tz.getFxzt()!=null&&"1".equals(tz.getFxzt())&&(tz.getFxcs()==null || "".equals(tz.getFxcs()) || "0".equals(tz.getFxcs()))) {
				ychkhgl += 1;
			}
			if(tz!=null && StringUtils.isNotBlank(tz.getFxpbh())) {
				//有返修
				ychkhglNot += 1;
			}

			if(tz!=null&&tz.getPs()!=null&&!"".equals(tz.getPs())) {
				ycppsl += Integer.valueOf(tz.getPs());
			}	
			if(tz!=null && tz.getZfxps()!=null && !"".equals(tz.getZfxps())) {
				bhgpsl += Integer.valueOf(tz.getZfxps());
				bhghks += 1;
			}
			if(tz!=null&&tz.getHkbh()!=null&&tz.getHkbh().startsWith("K")) {
				ktksl += 1;
				if(tz.getFxzt()!=null&&"1".equals(tz.getFxzt())) {
					kthgsl += 1;
				}
			}
		}
		//一次拍片合格率
		Double ycpphgl = Double.valueOf(ycppsl-ycbhgpsl)/Double.valueOf(ycppsl);
		
		BigDecimal bg = new BigDecimal(ycpphgl);
		ycpphgl = bg.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
		
		TzTj tt = new TzTj();
		tt.setGcmc(now.getSubProject().getProject().getName());
		tt.setSgdw(now.getSubProject().getProject().getSgdw());
		tt.setDwgc(now.getSubProject().getName());
		if(StringUtils.isNotBlank(sxy)) {
			tt.setSxy(sxy);
		}else {
			tt.setSxy("");
		}
		if(StringUtils.isNotBlank(gxh)) {
			tt.setGxh(gxh);
		}else {
			tt.setGxh("");
		}
		tt.setJcff(now.getJcff());
		tt.setHks(hks);
		tt.setBhghks(bhghks);
		Double ychkhgl_ = Double.valueOf(hks-ychkhglNot)/Double.valueOf(hks);
		BigDecimal bg2 = new BigDecimal(ychkhgl_);
		ychkhgl_ = bg2.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
		tt.setYchkhgl(ychkhgl_);
		tt.setYcppsl(ycppsl);
		tt.setBhgpsl(bhgpsl);
		tt.setYcpphgl(ycpphgl);
		tt.setKtksl(ktksl);
		tt.setKthgsl(kthgsl);
		tt.setYcbhgps(ycbhgpsl);
		tt.setJccd(0);
		return tt;
	}



	private Map<String, List<Tz>> renderTzMap(List<Tz> tzList) {
		Map<String, List<Tz>> result = Maps.newHashMap();
		for(Tz tz : tzList) {
			//修改为以单位工程为分组
			//String gxh = tz.getGxh();
			String dwgcId = tz.getSubProject().getId();
			List<Tz> tzTmp = (List<Tz>) result.get(dwgcId);
			if(tzTmp==null) {
				tzTmp = Lists.newArrayList();
			}
			tzTmp.add(tz);
			result.put(dwgcId, tzTmp);
		}
		return result;
	}
	
	
}
